<template>
    <div style="display: inline-block;">
        <el-select v-model="myId" clearable filterable remote reserve-keyword :placeholder="props.placeholder" :remote-method="remoteMethod" :loading="loading" style="width: 100%" @change="change1" :disabled="props.disabled">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
                <span v-if="props.property == 'forRiskCheckColumnId'">【{{ item.category }}】</span>
                <span class="inline-block m-r-sm" v-else-if="props.property == 'forIndexManagementId'">
                    <dynamicIndicator v-if="item.dictCalcMode=='2'" />
                    <staticIndicator v-else-if="item.dictCalcMode=='1'" />
                </span>
                <span>{{ item.name }}</span>
                <span class="pull-right rightStyle" v-if="hasRight">
                    <span v-if="props.property=='forPermCommonId'">{{ item.id }}</span>
                    <span v-else-if="props.property=='insideParam'">{{ item.value }}</span>
                    <span v-else> {{ item.code }}</span>
                </span>
            </el-option>
        </el-select>
    </div>
</template>
  
<script setup lang="ts">
import userApi from '@/api/system/user';
import roleApi from '@/api/system/role';
import pubApi from '@/api/pub';
import dataControl from '@/api/dataControl/index.ts';
import supplyApi from '@/api/manage/supplier.ts';
import itemApi from '@/api/manage/item.ts';
import riskApi from '@/api/risk';
import flowApi from '@/api/flow';
import dataApi from '@/api/data';
import reportApi from '@/api/report';
import dynamicIndicator from '@/assets/cssIcons/dynamicIndicator.vue';
import staticIndicator from '@/assets/cssIcons/staticIndicator.vue';

interface ListItem {
    id: number | string | null;
    name: string;
    category?: string;
    code?: string;
    dictCalcMode?: string;
    value?: string;
    dictDataPermColumnType?: string; 
    dictionary?: string;
    columnCode?: string;
    columnName?: string;
    columnPath?: string;
}
const props = defineProps({
    property:String,
    defaultList:{
        type:Array as () => ListItem[],
        default:() => [] // 确保默认值是一个空数组
    },
    index:Number,
    placeholder:String,
    modelValue:[Number,String,null],// 绑定 v-model 的值，接受 number 和 string 类型
    forDataPermSourceId:{
        type:Number,
        default:null
    },
    forIndexId:{
        type:Number,
        default:null
    },
    riskSourceItem:{
        type:Object as () => Record<string,any> | null,
        default:null
    },
    disabled: {
        type: Boolean,
        default: false
    },
    forReProcDefId: {
        type:Number,
        default:0
    },
    dictIndexConfigType: {
        type: String,
        default: ''
    },
    dictCalcMode: {
        type: String,
        default: ''
    },
    dictDataPermColumnType: {
        type: String,
        default: ''
    },
    dictOutParamColumnType: {
        type: String,
        default: ''
    },
    dictDateFormat: {
        type: String,
        default: ''
    },
    dictCalcPeriod: {
        type: String,
        default: ''
    },
    excludeIndexId: {
        type:Number,
        default:0
    },
    excludeIndexIds: {
        type:Array as () => any[],
        default:() => [] // 确保默认值是一个空数组
    },
    customizeList:{
        type:Array as () => ListItem[],
        default:() => []
    },
    dictDeptCfgCategory: {
        type: String,
        default: ''
    },
    formColumnInfoData: {
        type: Object as () => Record<string,any> | null,
        default:null
    }
});
const hasRight = ref(false);
const $emit = defineEmits(['update:modelValue','save']);// 定义 emit 事件

// 状态和观察者
const options = ref<ListItem[]>([]);
const myId = ref<string | number | null>(null);

watch(() => props.modelValue,(newVal) => {
    // console.log('回显Id:',newVal);
    myId.value = newVal?newVal:'';// 同步外部状态到内部状态
},{ immediate:true, deep: true  });

watch(() => props.defaultList, (newVal?:ListItem[], oldVal?:ListItem[]) => {
    if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;

    if (Array.isArray(newVal) && newVal.length > 0 && newVal[0].id) {
        myId.value = newVal[0].id;
        options.value = newVal.slice();
    }
}, { immediate: true, deep: true });

const loading = ref(false)

onMounted(() => {
    init()
})
const init = async() => {
    // 保留其他初始化逻辑，如清空状态等
    if (!props.defaultList || props.defaultList.length === 0) {
        myId.value = '';
        options.value = [];
    }
}
const remoteMethod = async (query: string) => {
    options.value = []
    hasRight.value = false;
    if(props.property == 'forUserId'){ // 用户
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await userApi.userSelect(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forRoleId'){ //角色
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await roleApi.roleSelect(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forRiskCheckColumnId'){ 
        try {
            loading.value = true;
            let results = await pubApi.riskColumnSelect({
                "searchKey": query, 
                "isWhiteColumn": 0
            }) as any;
            if (results) {
                if (results && results.length>0) {
                    results.forEach((item: any)=> {
                        options.value.push({
                            id: item.id,
                            name: item.name,
                            code: item.id,
                            category: item.category,
                            // dictDataPermColumnType: item.dictDataPermColumnType,
                            // dictionary: item.dictionary,
                        })
                    });
                    hasRight.value = true;
                }
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forIndexManagementId'){
        try {
            loading.value = true;
            let results = await pubApi.indexSelect({
                "searchKey": query,
                "dictIndexConfigType": props.dictIndexConfigType?props.dictIndexConfigType:null,
                "dictCalcMode": props.dictCalcMode?props.dictCalcMode:null,
                "dictOutParamColumnType": props.dictOutParamColumnType?props.dictOutParamColumnType:null,
                "excludeIndexId": props.excludeIndexId?props.excludeIndexId:null,
                "excludeIndexIds": props.excludeIndexIds,
            }) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forPermCommonId'){
        if(!props.forDataPermSourceId){
            ElMessage.error('缺少forDataPermSourceId');
            return;
        }
        try {
            loading.value = true;
            let results = await dataControl.searchCommon({
                "sourceId": props.forDataPermSourceId,
                "searchKey": query,
            }) as any;
            if (results) {
                options.value = results.data;
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forIndexParamId'){
        if(!props.forIndexId){
            ElMessage.error('请先选择指标');
            return;
        }
        try {
            loading.value = true;
            let results = await pubApi.indexParamSelect({
                "searchKey": query,
                "forIndexId": props.forIndexId,
                "dictParamTransferStruct": "1",
            }) as any;
            if (results) {
                if (Array.isArray(results) && results.length > 0) {
                    options.value = results;
                    options.value.forEach((item:any)=>{
                        item.id = item.code
                    })
                    hasRight.value = true;
                }
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forRiskSourceId'){
        if(!props.riskSourceItem){
            ElMessage.error('请先选择指标管理参数');
            return
        }
        const riskSourceItemObj = props.riskSourceItem;
        try {
            loading.value = true;
            let results = await pubApi.riskSourceSelect({
                "searchKey": query,
                "code": riskSourceItemObj.code,
                "dictDataPermColumnType": riskSourceItemObj.dictDataPermColumnType,
                "forRiskCheckColumnId": riskSourceItemObj.forRiskCheckColumnId
            }) as any;
            if (results&&results.length>0){
                results.forEach((item: { value: any; name: any; }) => {
                    options.value.push({
                        id: item.value,
                        name: item.name,
                    })
                });
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'dictClassCode'){
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await pubApi.dictSelect(searchKey, 1,40) as any;
            if (results) {
                results.records.forEach((item: any) => {
                    options.value.push({
                        id: item.classCode,
                        name: item.className
                    })
                });
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forSupplierId'){ //供应商
        try {
            loading.value = true;
            let results = await supplyApi.postSupplierList(1,9999,{
                "searchKey": query ? query : '',
            }) as any;
            if (results) {
                options.value = results.records;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forItemId'){//物品
        try {
            loading.value = true;
            let results = await itemApi.postItemList(1,9999,{
                "searchKey": query ? query : '',
            }) as any;
            if (results) {
                options.value = results.records;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forRiskBusinessId'){ //风控项目
        try {
            loading.value = true;
            let results = await riskApi.selectRiskBusiness({
                "searchKey": query,
            }) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'turnAround'){ //流程图连线-指定业务方法
        try {
            loading.value = true;
            let results = await flowApi.selectTurnAroundMethod( query?query:'') as any;
            if (results && results.length>0) {
                results.forEach((item: { leftValue: any; rightValue: any; }) => {
                    options.value.push({
                        id: item.leftValue,
                        name: item.leftValue,
                        code: item.rightValue
                    })
                });
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'startCheck'){ //流程图节点-启动校验-指定业务方法
        try {
            loading.value = true;
            let results = await flowApi.selectStartCheckMethod( query?query:'') as any;
            if (results && results.length>0) {
                results.forEach((item: { leftValue: any; rightValue: any; }) => {
                    options.value.push({
                        id: item.leftValue,
                        name: item.leftValue,
                        code: item.rightValue
                    })
                });
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'formColumn'){ //审核人-人工指定表单字段
        try {
            loading.value = true;
            let results = await flowApi.selectFormColumn( props.forReProcDefId, query?query:'') as any;
            if (results && results.length>0) {
                results.forEach((item: { leftValue: any; rightValue: any; }) => {
                    options.value.push({
                        id: item.leftValue,
                        name: item.leftValue,
                        code: item.rightValue
                    })
                });
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'candidate'){ //审核人-自定义方法
        try {
            loading.value = true;
            let results = await flowApi.selectCandidateMethod( query?query:'') as any;
            if (Array.isArray(results) && results.length > 0) {
                options.value = results.map((item: { leftValue: any; rightValue: any; }) => ({
                    id: item.leftValue,
                    name: item.leftValue,
                    code: item.rightValue
                }));
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'paramDef'){ 
        try {
            loading.value = true;
            let results = await pubApi.paramDefSelect(1, 20, {
                "searchKey": query,
                "dictDataPermColumnType": null,
                "forDataPermSourceId": null
            }) as any;
            options.value = results.records;
            hasRight.value = true;
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forDataPermSourceId'){ 
        try {
            loading.value = true;
            let results = await pubApi.dacSourceSelect(1, 20, {
                dictDataPermSourceType: "1",
                searchKey: query
            }) as any;
            options.value = results.records;
            hasRight.value = true;
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'insideParam'){ //内置参数
        if(!props.dictDateFormat){
            ElMessage.error('请先选择日期格式');
            return
        }
        let searchKey = query ? query : '';
        let dictCalcPeriod = props.dictCalcPeriod ? props.dictCalcPeriod : '';
        let dictCalcMode = props.dictCalcMode ? props.dictCalcMode : '';
        try {
            loading.value = true;
            let results = await pubApi.commonInsideParam(`dictDataParamColumnType=${props.dictDataPermColumnType}&dictDateFormat=${
                props.dictDateFormat}&searchKey=${searchKey}&dictCalcPeriod=${dictCalcPeriod}&dictCalcMode=${dictCalcMode}`) as any;
            if (results) {
                options.value = results;
                if (Array.isArray(options.value)) {
                    options.value.forEach((optionItem: any) => {
                        optionItem.id = optionItem.code;
                        optionItem.name = optionItem.showName ?? ''; // 可选：添加默认值防止 undefined
                    });
                }
            }
            hasRight.value = true;
        } catch (error) {
            throw new Error("接口调用失败");
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forDataSourceViewId'){  //资源视图下拉框
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await pubApi.selectDataSourceView(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forDataSourceReportId'){  //资源报表下拉框
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await pubApi.selectDataSourceReport(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forDataPermSourceViewId'){ 
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await dataApi.getViewRelationSelect(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forDataPermConfigId'){ 
        try {
            loading.value = true;
            let results = await dataControl.getDataPermConfig(1, 20, {
                searchKey: query
            }) as any;
            if (results) {
                options.value = results.records;
            }
            hasRight.value = true;
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'riskIndexSelect'){ 
        if(!props.dictDeptCfgCategory){
            ElMessage.error('请先选择部门');
            return;
        }
        try {
            loading.value = true;
            let results = await riskApi.selectRiskIndex({
                "dictDeptCfgCategory": props.dictDeptCfgCategory,
                "dictRiskCheckType": "1",
                "searchKey": query,
            }) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'formColumnInfo'){ 
        try {
            loading.value = true;
            let results = await flowApi.selectFormColumnInfo(
                `procDefId=${props.forReProcDefId}&searchKey=${query ? query : ''}&code=${
                    props.formColumnInfoData?.code ?? ''
                }&dictDataPermColumnType=${
                    props.formColumnInfoData?.dictDataPermColumnType ?? ''
                }&forDataPermSourceId=${
                    props.formColumnInfoData?.forDataPermSourceId ?? ''
                }&classCode=${
                    props.formColumnInfoData?.classCode ?? ''
                }&dictDateFormat=${
                    props.formColumnInfoData?.dictDateFormat ?? ''
                }&isMoreValue=${props.formColumnInfoData?.isMoreValue ?? ''}`
            ) as any;
            if (results && results.length>0) {
                options.value = results;
                options.value.forEach((item: any) => {
                    item.id = item.columnPath;
                    item.name = item.columnName;
                    item.code = item.columnPath;
                });
                console.log(options.value);
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'productCode'){ // 基金
        try {
            loading.value = true;
            let results = await reportApi.selectFundProductInfo( {
                "keyWord": query
            }) as any;
            if (results && results.length>0) {
                results.forEach((item: any) => {
                    options.value.push({
                        id: item.product_code,
                        name: item.product_name,
                        code: item.product_code
                    })
                });
                hasRight.value = true;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == ''){
        options.value = props.customizeList;
    }
}
const change1 = (val: any) => {
    // 查找options中id 与 val 匹配的对象
    const selectedOption = options.value.find(item => item.id === val);
    let msg = {
        property: props.property,
        index: props.index, 
        value: val,
        item: selectedOption
    };
    $emit('update:modelValue',val);// 触发 v-model 更新
    $emit('save',  JSON.parse(JSON.stringify(msg)));
}
const clear = () =>{
    myId.value = '';
    options.value = [];
}
defineExpose({ clear});
</script>
  
<style scoped lang="scss">
.rightStyle{ padding-left: 20px;color: var(--el-text-color-secondary);}
</style>
